<template>
  <div class="device-diagnostic">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>🔧 设备通道认证诊断工具</span>
          <el-tag type="info">Terminal#906-949 问题快速诊断与修复</el-tag>
        </div>
      </template>
      
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 单设备诊断 -->
        <el-tab-pane label="单设备诊断" name="single">
          <div class="section">
            <h3>🔍 单设备诊断</h3>
            <el-form :model="singleForm" label-width="120px">
              <el-form-item label="设备ID">
                <el-input v-model="singleForm.deviceId" placeholder="请输入设备ID" />
              </el-form-item>
              <el-form-item label="选择设备">
                <el-select 
                  v-model="singleForm.selectedDevice" 
                  placeholder="搜索或选择设备" 
                  filterable
                  clearable
                  @change="selectDevice"
                  @clear="clearDevice">
                  <el-option-group v-if="recentDevices.length > 0" label="最近使用">
                    <el-option
                      v-for="device in recentDevices"
                      :key="'recent-' + device.id"
                      :label="`${device.name} (${device.ipAddress})`"
                      :value="device.id">
                      <div class="device-option">
                        <span class="status-indicator" :class="getDeviceStatusClass(device)"></span>
                        <span class="device-name">{{ device.name }}</span>
                        <span class="device-ip">{{ device.ipAddress }}</span>
                        <el-tag size="small" type="info">最近使用</el-tag>
                      </div>
                    </el-option>
                  </el-option-group>
                  <el-option-group label="所有设备">
                    <el-option
                      v-for="device in filteredDevices"
                      :key="device.id"
                      :label="`${device.name} (${device.ipAddress})`"
                      :value="device.id">
                      <div class="device-option">
                        <span class="status-indicator" :class="getDeviceStatusClass(device)"></span>
                        <span class="device-name">{{ device.name }}</span>
                        <span class="device-ip">{{ device.ipAddress }}</span>
                        <el-tag v-if="device.hasIssues" size="small" type="warning">有问题</el-tag>
                      </div>
                    </el-option>
                  </el-option-group>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button-group>
                  <el-button type="primary" @click="diagnoseDevice" :loading="singleLoading">
                    {{ singleLoading ? '诊断中...' : '开始诊断' }}
                  </el-button>
                  <el-button 
                    type="success" 
                    @click="quickDiagnose" 
                    :loading="singleLoading"
                    :disabled="!singleForm.selectedDevice">
                    <el-icon><Lightning></Lightning></el-icon>
                    快速诊断
                  </el-button>
                  <el-button 
                    type="info" 
                    @click="showDiagnosticHistory" 
                    :disabled="!singleForm.selectedDevice">
                    <el-icon><Clock></Clock></el-icon>
                    历史记录
                  </el-button>
                </el-button-group>
                <el-button @click="getSuggestions">
                  💡 获取建议
                </el-button>
                <el-button @click="loadDevices">
                  🔄 刷新设备列表
                </el-button>
              </el-form-item>
            </el-form>
            
            <!-- 诊断进度 -->
            <div v-if="singleLoading" class="progress-container">
              <el-card>
                <div class="progress-header">
                  <h4>正在诊断设备...</h4>
                  <el-tag type="info">{{ diagnosticProgress.currentStep }}</el-tag>
                </div>
                <el-progress 
                  :percentage="diagnosticProgress.percentage" 
                  :status="diagnosticProgress.status"
                  :stroke-width="8">
                </el-progress>
                <div class="progress-steps">
                  <div 
                    v-for="(step, index) in diagnosticProgress.steps" 
                    :key="index"
                    class="step-item"
                    :class="{
                      'completed': step.status === 'completed',
                      'running': step.status === 'running',
                      'pending': step.status === 'pending'
                    }">
                    <el-icon v-if="step.status === 'completed'" class="step-icon success"><Check></Check></el-icon>
            <el-icon v-else-if="step.status === 'running'" class="step-icon running"><Loading></Loading></el-icon>
            <el-icon v-else class="step-icon pending"><Clock></Clock></el-icon>
                    <span class="step-text">{{ step.name }}</span>
                    <span v-if="step.duration" class="step-duration">{{ step.duration }}ms</span>
                  </div>
                </div>
              </el-card>
            </div>

            <!-- 诊断结果 -->
            <div v-if="singleResult" class="result-container">
              <el-card>
                <div class="result-header">
                  <el-alert
                    :title="singleResult.title"
                    :type="singleResult.type"
                    :description="singleResult.description"
                    show-icon
                    :closable="false"
                  />
                  <div class="result-actions">
                    <el-button size="small" @click="exportDiagnosticReport">
                      <el-icon><Download></Download></el-icon>
                      导出报告
                    </el-button>
                    <el-button size="small" @click="shareDiagnosticResult">
                      <el-icon><Share></Share></el-icon>
                      分享结果
                    </el-button>
                  </div>
                </div>
                
                <!-- 快速操作面板 -->
                <div v-if="!singleResult.success" class="quick-actions">
                  <h4>建议操作：</h4>
                  <el-space wrap>
                    <el-button 
                      v-for="action in suggestedActions" 
                      :key="action.type"
                      :type="action.buttonType"
                      size="small"
                      @click="executeQuickAction(action)">
                      <el-icon><component :is="action.icon" /></el-icon>
                      {{ action.label }}
                    </el-button>
                  </el-space>
                </div>

                <div v-if="singleResult.details" class="result-details">
                  <el-tabs v-model="activeResultTab">
                    <el-tab-pane label="概览" name="overview">
                      <div class="result-overview">
                        <el-row :gutter="16">
                          <el-col :span="8">
                            <el-statistic title="响应时间" :value="singleResult.responseTime" suffix="ms" />
                          </el-col>
                          <el-col :span="8">
                            <el-statistic title="成功率" :value="singleResult.successRate" suffix="%" />
                          </el-col>
                          <el-col :span="8">
                            <el-statistic title="检查项目" :value="singleResult.totalChecks" />
                          </el-col>
                        </el-row>
                      </div>
                    </el-tab-pane>
                    <el-tab-pane label="详细信息" name="details">
                      <el-descriptions :column="2" border>
                        <el-descriptions-item
                          v-for="(value, key) in singleResult.details"
                          :key="key"
                          :label="key"
                        >
                          {{ value }}
                        </el-descriptions-item>
                      </el-descriptions>
                    </el-tab-pane>
                    <el-tab-pane label="性能指标" name="metrics">
                      <div class="metrics-chart">
                        <!-- 这里可以添加图表组件 -->
                        <p>性能指标图表（待实现）</p>
                      </div>
                    </el-tab-pane>
                  </el-tabs>
                </div>
              </el-card>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 批量诊断 -->
        <el-tab-pane label="批量诊断" name="batch">
          <div class="section">
            <h3>📊 批量设备诊断</h3>
            <el-form :model="batchForm" label-width="120px">
              <el-form-item label="设备ID列表">
                <el-input
                  v-model="batchForm.deviceIds"
                  type="textarea"
                  :rows="5"
                  placeholder="请输入设备ID，每行一个"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="batchDiagnose" :loading="batchLoading">
                  🚀 批量诊断
                </el-button>
                <el-button @click="selectAllDevices">
                  📋 选择所有设备
                </el-button>
              </el-form-item>
            </el-form>
            
            <div v-if="batchResults.length > 0" class="batch-results">
              <h4>📈 批量诊断结果</h4>
              <el-table :data="batchResults" border>
                <el-table-column prop="deviceId" label="设备ID" width="120" />
                <el-table-column prop="deviceName" label="设备名称" width="150" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getStatusType(row.status)">{{ row.status }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="message" label="诊断信息" />
                <el-table-column label="操作" width="120">
                  <template #default="{ row }">
                    <el-button size="small" @click="viewDetails(row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 统计信息 -->
        <el-tab-pane label="统计信息" name="statistics">
          <div class="section">
            <h3>📈 系统诊断统计</h3>
            <el-button @click="loadStatistics" :loading="statisticsLoading">
              🔄 刷新统计
            </el-button>
            
            <div v-if="statistics" class="statistics-content">
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-statistic title="总设备数" :value="statistics.totalDevices" />
                </el-col>
                <el-col :span="6">
                  <el-statistic title="在线设备" :value="statistics.onlineDevices" />
                </el-col>
                <el-col :span="6">
                  <el-statistic title="离线设备" :value="statistics.offlineDevices" />
                </el-col>
                <el-col :span="6">
                  <el-statistic title="异常设备" :value="statistics.errorDevices" />
                </el-col>
              </el-row>
            </div>
          </div>
        </el-tab-pane>
        
        <!-- 帮助文档 -->
        <el-tab-pane label="帮助文档" name="help">
          <div class="section">
            <h3>📚 帮助文档</h3>
            
            <el-collapse v-model="activeHelp">
              <el-collapse-item title="❌ 401认证失败" name="auth-fail">
                <ul>
                  <li>检查设备用户名和密码是否正确</li>
                  <li>确认用户是否有ONVIF访问权限</li>
                  <li>尝试使用Basic认证替代Digest认证</li>
                  <li>检查设备认证方式设置</li>
                </ul>
              </el-collapse-item>
              
              <el-collapse-item title="🌐 网络连接问题" name="network">
                <ul>
                  <li>检查设备IP地址是否正确</li>
                  <li>确认网络连接是否正常</li>
                  <li>检查防火墙设置</li>
                  <li>验证设备端口是否开放</li>
                </ul>
              </el-collapse-item>
              
              <el-collapse-item title="⏱️ 连接超时" name="timeout">
                <ul>
                  <li>增加连接超时时间</li>
                  <li>检查网络延迟</li>
                  <li>确认设备负载情况</li>
                  <li>尝试重启设备ONVIF服务</li>
                </ul>
              </el-collapse-item>
              
              <el-collapse-item title="🔧 ONVIF服务不可用" name="service">
                <ul>
                  <li>确认设备是否支持ONVIF协议</li>
                  <li>检查ONVIF服务是否启用</li>
                  <li>验证服务路径是否正确</li>
                  <li>更新设备固件版本</li>
                </ul>
              </el-collapse-item>
            </el-collapse>
            
            <div class="config-example">
              <h4>🛠️ 配置优化建议</h4>
              <el-alert
                title="application-device-config.yml 优化配置"
                type="info"
                :closable="false"
              >
                <pre>device-config:
  default:
    connectionTimeout: 10000
    readTimeout: 10000
    preferredAuthMethods: ["Basic", "Digest", "None"]
    useHeadForDigest: false
    maxRetries: 3
    retryDelay: 2000</pre>
              </el-alert>
            </div>
            
            <div class="support-info">
              <h4>📞 技术支持</h4>
              <p>如果问题仍然存在，请联系技术支持并提供以下信息：</p>
              <ul>
                <li>设备型号和固件版本</li>
                <li>完整的错误日志</li>
                <li>网络拓扑图</li>
                <li>诊断报告结果</li>
              </ul>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAllDevices, getDeviceById } from '@/api/device'
import { 
  Lightning, Clock, Check, Loading, Download, Share, 
  Refresh, Tools, Warning, Setting 
} from '@element-plus/icons-vue'



// 响应式数据
const activeTab = ref('single')
const activeHelp = ref(['auth-fail'])

const devices = ref([])
const recentDevices = ref([])
const singleForm = reactive({
  deviceId: '',
  selectedDevice: ''
})

const batchForm = reactive({
  deviceIds: ''
})

const singleLoading = ref(false)
const batchLoading = ref(false)
const statisticsLoading = ref(false)

// 诊断进度数据
const diagnosticProgress = reactive({
  percentage: 0,
  status: '',
  currentStep: '',
  steps: [
    { name: '连接测试', status: 'pending', duration: null },
    { name: '设备信息获取', status: 'pending', duration: null },
    { name: '功能检测', status: 'pending', duration: null },
    { name: '性能测试', status: 'pending', duration: null },
    { name: '生成报告', status: 'pending', duration: null }
  ]
})

// 结果展示相关
const activeResultTab = ref('overview')
const suggestedActions = ref([])

const singleResult = ref(null)
const batchResults = ref([])
const statistics = ref(null)

// 计算属性
const filteredDevices = computed(() => {
  return devices.value.filter(device => 
    !recentDevices.value.some(recent => recent.id === device.id)
  )
})

// 设备状态相关方法
const getDeviceStatusClass = (device) => {
  if (device.status === 'online') return 'status-online'
  if (device.status === 'offline') return 'status-offline'
  return 'status-unknown'
}

const clearDevice = () => {
  singleForm.selectedDevice = ''
  singleForm.deviceId = ''
}

const quickDiagnose = async () => {
  if (!singleForm.selectedDevice) {
    ElMessage.warning('请先选择设备')
    return
  }
  
  singleLoading.value = true
  // 模拟快速诊断进度
  updateDiagnosticProgress()
  
  try {
    // 模拟快速诊断响应
    await new Promise(resolve => setTimeout(resolve, 2000))
    const response = {
      success: true,
      message: '设备连接正常，所有功能检测通过',
      responseTime: 150,
      successRate: 95,
      totalChecks: 8
    }
    singleResult.value = {
      title: '快速诊断完成',
      type: response.success ? 'success' : 'error',
      description: response.message,
      responseTime: response.responseTime || 0,
      successRate: response.successRate || 0,
      totalChecks: response.totalChecks || 0,
      details: response.details
    }
  } catch (error) {
    singleResult.value = {
      title: '快速诊断失败',
      type: 'error',
      description: error.message
    }
  } finally {
    singleLoading.value = false
  }
}

const showDiagnosticHistory = () => {
  ElMessage.info('诊断历史功能开发中...')
}

const updateDiagnosticProgress = () => {
  let currentStep = 0
  const totalSteps = diagnosticProgress.steps.length
  
  const updateStep = () => {
    if (currentStep < totalSteps) {
      // 更新当前步骤状态
      if (currentStep > 0) {
        diagnosticProgress.steps[currentStep - 1].status = 'completed'
        diagnosticProgress.steps[currentStep - 1].duration = Math.floor(Math.random() * 1000) + 500
      }
      
      diagnosticProgress.steps[currentStep].status = 'running'
      diagnosticProgress.currentStep = diagnosticProgress.steps[currentStep].name
      diagnosticProgress.percentage = Math.floor((currentStep / totalSteps) * 100)
      
      currentStep++
      
      if (currentStep <= totalSteps) {
        setTimeout(updateStep, 1000 + Math.random() * 1000)
      } else {
        diagnosticProgress.steps[totalSteps - 1].status = 'completed'
        diagnosticProgress.percentage = 100
        diagnosticProgress.status = 'success'
      }
    }
  }
  
  updateStep()
}

const exportDiagnosticReport = () => {
  ElMessage.success('报告导出功能开发中...')
}

const shareDiagnosticResult = () => {
  ElMessage.success('分享功能开发中...')
}

const executeQuickAction = (action) => {
  ElMessage.info(`执行操作: ${action.label}`)
}

// 方法
const loadDevices = async () => {
  try {
    const response = await getAllDevices()
    devices.value = response.data || []
    
    // 加载最近使用的设备
    const savedRecentDevices = localStorage.getItem('recentDiagnosticDevices')
    if (savedRecentDevices) {
      const recentIds = JSON.parse(savedRecentDevices)
      recentDevices.value = recentIds.filter(recent => 
        devices.value.some(device => device.id === recent.id)
      )
    }
    
    // 检测设备状态和问题
    await detectDeviceIssues()
    
    ElMessage.success('设备列表已刷新')
  } catch (error) {
    console.error('加载设备列表失败:', error)
    ElMessage.error('加载设备列表失败: ' + error.message)
  }
}

const detectDeviceIssues = async () => {
  // 为设备添加状态和问题标识
  devices.value.forEach(device => {
    // 模拟设备状态检测
    device.status = Math.random() > 0.2 ? 'online' : 'offline'
    device.hasIssues = Math.random() > 0.8
    
    // 根据设备状态生成建议操作
    if (device.status === 'offline' || device.hasIssues) {
      updateSuggestedActions(device)
    }
  })
}

const updateSuggestedActions = (device) => {
  const actions = []
  
  if (device.status === 'offline') {
    actions.push(
      { type: 'reconnect', label: '重新连接', icon: 'Refresh', buttonType: 'primary' },
      { type: 'ping', label: '网络测试', icon: 'Tools', buttonType: 'info' }
    )
  }
  
  if (device.hasIssues) {
    actions.push(
      { type: 'repair', label: '自动修复', icon: 'Tools', buttonType: 'warning' },
      { type: 'config', label: '检查配置', icon: 'Setting', buttonType: 'default' }
    )
  }
  
  suggestedActions.value = actions
}

const selectDevice = (deviceId) => {
  if (deviceId) {
    singleForm.deviceId = deviceId
    singleForm.selectedDevice = deviceId
  } else {
    singleForm.deviceId = singleForm.selectedDevice
  }
  singleResult.value = null
  
  // 添加到最近使用设备
  const selectedDeviceId = deviceId || singleForm.selectedDevice
  const selectedDevice = devices.value.find(d => d.id === selectedDeviceId)
  if (selectedDevice) {
    // 移除已存在的记录
    const existingIndex = recentDevices.value.findIndex(d => d.id === selectedDeviceId)
    if (existingIndex > -1) {
      recentDevices.value.splice(existingIndex, 1)
    }
    
    // 添加到开头，最多保留5个
    recentDevices.value.unshift(selectedDevice)
    if (recentDevices.value.length > 5) {
      recentDevices.value.pop()
    }
    
    // 保存到本地存储
    localStorage.setItem('recentDiagnosticDevices', JSON.stringify(recentDevices.value))
  }
}

const diagnoseDevice = async () => {
  if (!singleForm.deviceId.trim()) {
    ElMessage.warning('请输入设备ID')
    return
  }
  
  singleLoading.value = true
  singleResult.value = null
  
  try {
    // 模拟启动异步诊断任务
    await new Promise(resolve => setTimeout(resolve, 1000))
    const response = { success: true, taskId: 'task_' + Date.now() }
    
    if (response.success) {
      ElMessage.info('诊断任务已启动，正在执行中...')
      // 轮询获取结果
      pollDiagnosticResult(response.taskId)
    } else {
      singleResult.value = {
        title: '诊断失败',
        type: 'error',
        description: response.message || '启动诊断任务失败'
      }
      singleLoading.value = false
    }
  } catch (error) {
    console.error('启动诊断失败:', error)
    singleResult.value = {
      title: '诊断错误',
      type: 'error',
      description: '启动诊断任务失败: ' + error.message
    }
    singleLoading.value = false
  }
}

// 轮询获取异步诊断结果
const pollDiagnosticResult = async (taskId) => {
  const maxAttempts = 30 // 最多轮询30次（30秒）
  let attempts = 0
  
  const poll = async () => {
    attempts++
    
    try {
      // 模拟获取诊断结果
      await new Promise(resolve => setTimeout(resolve, 500))
      const response = {
        status: attempts > 5 ? 'COMPLETED' : 'RUNNING',
        result: {
          success: true,
          message: '设备诊断完成',
          details: {
            connectivity: { status: 'success', message: '网络连接正常' },
            authentication: { status: 'success', message: '认证成功' },
            capabilities: { status: 'success', message: '功能检测通过' }
          }
        }
      }
      
      if (response.status === 'COMPLETED') {
        singleLoading.value = false
        
        if (response.success) {
          singleResult.value = {
            title: '诊断完成',
            type: 'success',
            description: `设备 ${response.deviceName} 诊断完成 - ${response.resultDescription}`,
            details: {
              deviceId: response.deviceId,
              deviceName: response.deviceName,
              result: response.result,
              resultDescription: response.resultDescription,
              errorMessage: response.errorMessage,
              suggestions: response.suggestions,
              details: response.details,
              timestamp: response.timestamp
            }
          }
          ElMessage.success('诊断完成')
        } else {
          singleResult.value = {
            title: '诊断失败',
            type: 'error',
            description: response.errorMessage || '设备诊断失败'
          }
          ElMessage.error('诊断失败')
        }
      } else if (response.status === 'FAILED') {
        singleLoading.value = false
        singleResult.value = {
          title: '诊断失败',
          type: 'error',
          description: response.errorMessage || '诊断任务执行失败'
        }
        ElMessage.error('诊断失败')
      } else if (response.status === 'RUNNING') {
        // 任务仍在运行，继续轮询
        if (attempts < maxAttempts) {
          setTimeout(poll, 1000) // 1秒后再次轮询
        } else {
          // 超时
          singleLoading.value = false
          singleResult.value = {
            title: '诊断超时',
            type: 'warning',
            description: '诊断任务执行时间过长，请稍后手动查询结果'
          }
          ElMessage.warning('诊断超时，请稍后查询')
        }
      }
    } catch (error) {
      singleLoading.value = false
      singleResult.value = {
        title: '获取结果失败',
        type: 'error',
        description: '获取诊断结果失败: ' + error.message
      }
      ElMessage.error('获取诊断结果失败')
    }
  }
  
  // 开始轮询
  poll()
}

const getSuggestions = () => {
  ElMessageBox.alert(
    '请根据设备状态选择相应的解决方案：\n\n' +
    '1. 401认证失败 - 检查用户名密码\n' +
    '2. 网络连接问题 - 检查网络配置\n' +
    '3. 连接超时 - 调整超时设置\n' +
    '4. ONVIF服务不可用 - 检查设备支持',
    '诊断建议',
    {
      confirmButtonText: '确定'
    }
  )
}

const batchDiagnose = async () => {
  const deviceIds = batchForm.deviceIds.trim().split('\n').filter(id => id.trim())
  if (deviceIds.length === 0) {
    ElMessage.warning('请输入设备ID列表')
    return
  }
  
  batchLoading.value = true
  batchResults.value = []
  
  try {
    // 模拟批量诊断
    await new Promise(resolve => setTimeout(resolve, 3000))
    const response = {
      data: deviceIds.map(id => ({
        deviceId: id,
        status: Math.random() > 0.3 ? 'success' : 'error',
        message: Math.random() > 0.3 ? '诊断通过' : '连接失败',
        responseTime: Math.floor(Math.random() * 500) + 100
      }))
    }
    batchResults.value = response.data || []
    ElMessage.success('批量诊断完成')
  } catch (error) {
    console.error('批量诊断失败:', error)
    ElMessage.error('批量诊断失败: ' + error.message)
  } finally {
    batchLoading.value = false
  }
}

const selectAllDevices = () => {
  const deviceIds = devices.value.map(device => device.id).join('\n')
  batchForm.deviceIds = deviceIds
  ElMessage.success('已选择所有设备')
}

const loadStatistics = async () => {
  statisticsLoading.value = true
  
  try {
    // 模拟获取统计信息
    await new Promise(resolve => setTimeout(resolve, 1000))
    const response = {
      data: {
        totalDevices: 25,
        onlineDevices: 22,
        offlineDevices: 3,
        healthyDevices: 20,
        warningDevices: 2,
        errorDevices: 3,
        avgResponseTime: 145,
        successRate: 88
      }
    }
    statistics.value = response.data
    ElMessage.success('统计信息已刷新')
  } catch (error) {
    console.error('加载统计信息失败:', error)
    ElMessage.error('加载统计信息失败: ' + error.message)
  } finally {
    statisticsLoading.value = false
  }
}

const getStatusType = (status) => {
  switch (status) {
    case '正常': return 'success'
    case '异常': return 'danger'
    case '警告': return 'warning'
    default: return 'info'
  }
}

const viewDetails = (row) => {
  ElMessageBox.alert(
    JSON.stringify(row, null, 2),
    '设备诊断详情',
    {
      confirmButtonText: '确定'
    }
  )
}

// 生命周期
onMounted(() => {
  loadDevices()
})
</script>

<style scoped>
.device-diagnostic {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section {
  padding: 20px 0;
}

.section h3 {
  margin-bottom: 20px;
  color: #409eff;
}

/* 设备选择优化样式 */
.device-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.status-indicator {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  display: inline-block;
}

.status-online {
  background-color: #67c23a;
}

.status-offline {
  background-color: #f56c6c;
}

.status-unknown {
  background-color: #e6a23c;
}

.device-name {
  font-weight: 500;
  flex: 1;
}

.device-ip {
  color: #909399;
  font-size: 12px;
}

/* 进度显示样式 */
.progress-container {
  margin-top: 20px;
}

.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.progress-steps {
  margin-top: 16px;
}

.step-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-left: 2px solid #e4e7ed;
  padding-left: 16px;
  margin-left: 8px;
}

.step-item.completed {
  border-left-color: #67c23a;
}

.step-item.running {
  border-left-color: #409eff;
  background-color: #f0f9ff;
}

.step-item.pending {
  border-left-color: #e4e7ed;
  color: #909399;
}

.step-icon.success {
  color: #67c23a;
}

.step-icon.running {
  color: #409eff;
}

.step-icon.pending {
  color: #c0c4cc;
}

.step-text {
  flex: 1;
  font-weight: 500;
}

.step-duration {
  font-size: 12px;
  color: #909399;
}

/* 结果展示样式 */
.result-container {
  margin-top: 20px;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.result-actions {
  display: flex;
  gap: 8px;
}

.quick-actions {
  margin: 16px 0;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #e6a23c;
}

.quick-actions h4 {
  margin: 0 0 12px 0;
  color: #e6a23c;
  font-size: 14px;
}

.result-overview {
  padding: 16px 0;
}

.result-json {
  background: #f5f5f5;
  padding: 16px;
  border-radius: 8px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  max-height: 400px;
  overflow-y: auto;
}

.metrics-chart {
  padding: 32px;
  text-align: center;
  color: #909399;
}

.result-details {
  margin-top: 15px;
}

.batch-results {
  margin-top: 20px;
}

.statistics-content {
  margin-top: 20px;
}

.config-example {
  margin-top: 20px;
}

.config-example pre {
  background: #f5f5f5;
  padding: 10px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
}

.support-info {
  margin-top: 20px;
}

.support-info ul {
  margin-left: 20px;
}

.support-info li {
  margin-bottom: 5px;
}

.el-form {
  max-width: 600px;
}

.el-collapse {
  margin-top: 10px;
}

.el-collapse-item ul {
  margin-left: 20px;
}

.el-collapse-item li {
  margin-bottom: 5px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .device-diagnostic {
    padding: 10px;
  }
  
  .result-header {
    flex-direction: column;
    gap: 12px;
  }
  
  .result-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .device-option {
    flex-wrap: wrap;
  }
  
  .step-item {
    padding-left: 12px;
    margin-left: 6px;
  }
}
</style>